<?php
class Pageley_I18n_BasicDictionary implements Pageley_I18n_Dictionary {
    private $localeMap;
    private $defaultLocale;
    
    public function __construct($localeMap, $defaultLocale) {
        $this->localeMap = $localeMap;
        $this->defaultLocale = $defaultLocale;
    }
    
    public function translate($locale, $key, $parameters = null) {
        $pages = null;
        if($locale !== null) {
            $pages = $this->localeMap->get($locale->getCode());
        }
        if($pages === null) {
            $pages = $this->localeMap->get($this->defaultLocale);
            if($pages === null) {
                throw new Pageley_I18n_Exception("No pages defined for default locale " . $this->defaultLocale . ".");
            }
        }
        $pageName = Pageley_Util_String::substringBefore($key, ".");
        $wordKey = Pageley_Util_String::substringAfter($key, ".");
        $page = $pages->get($pageName);
        if($page === null) {
            throw new Pageley_I18n_Exception("Page " . $pageName . " does not exist for locale " . $locale . ".");
        }
        $translation = $page->translate($wordKey);
        if($translation === null) {
            $translation = "???" . $key . "???";
            Pageley_Log::warn($this, "No translation found in locale '" . $locale . "' for key '" . $key . "'.");
        }
        if($parameters !== null) {
            foreach($parameters as $index => $value) {
                $translation = preg_replace("/\{" . $index . "\}/", $value, $translation);
            }
        }
        $matches = array();
        preg_match_all("/\{([a-zA-Z][\w.]+)\}/", $translation, $matches);
        foreach($matches[1] as $match) {
        	$pattern = preg_replace("/\./" , "\.", $match);
            $translation = preg_replace("/\{" . $pattern . "\}/", $this->translate($locale, $match), $translation);
        }
        return $translation;
    }
}